# 项目名：小说爬取
# 作者：张见葛
# 该文件主要是一些打印相关的方法

import time
from rich.progress import BarColumn, TimeRemainingColumn, Progress
import sys
import _thread

Global = {}


# 更新进度
def update_progress(info=None):
    Global['num'] = Global['num'] + 1
    Global['info'] = info


# 开始进度UI的初始化
def set_progress(total, step_size=1):
    Global['total'] = total
    Global['step_size'] = step_size
    Global['num'] = 0
    try:
        Global['info'] = '开始查询需要下载的列表'
        _thread.start_new_thread(progress_ui, (total,))
    except:
        print("Error: 无法启动progress线程，正在退出")
        sys.exit(0)


# 生成UI
def progress_ui(total):
    progress = Progress("{task.description}",
                        BarColumn(),
                        "{task.percentage:>3.0f}%",
                        TimeRemainingColumn(),
                        "{task.completed}/{task.total}")
    with progress:
        Global['task_id'] = progress.add_task("[green]下载中...", total=total)
        Global['progress'] = progress
        while True:
            if Global['info'] is not None:
                Global['progress'].tasks[Global['task_id']].description = '[green]下载中...(' + Global['info'] + ')'
            else:
                Global['progress'].tasks[Global['task_id']].description = '[green]下载中...'
            Global['progress'].update(Global['task_id'],
                                      advance=Global['num'] - Global['progress'].tasks[Global['task_id']].completed)
            if Global['progress'].tasks[Global['task_id']].completed >= total:
                break
            time.sleep(0.3)
